package com.salton123.soulove.sailfish.video.ui.adapter

import android.text.format.Formatter
import android.widget.CheckBox
import android.widget.ImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.salton123.soulove.app.R
import com.salton123.soulove.sailfish.db.VideoItem
import com.salton123.soulove.utils.Utils
import com.salton123.utils.ImageLoader

/**
 * Time:2021/9/13 11:15 上午
 * Author:
 * Description:
 */
class VideoBatchAdapter : BaseQuickAdapter<VideoItem, BaseViewHolder>(R.layout.adapter_item_batch_operate) {

    private val selectedItems: HashMap<String, VideoItem> = hashMapOf()
    var onCheckChanged: ((count: Int) -> Unit)? = null
    override fun convert(holder: BaseViewHolder, item: VideoItem) {
        val cbSelected = holder.getView<CheckBox>(R.id.cbSelected)
        cbSelected.isChecked = false
        selectedItems[item.filePath]?.let {
            //此item已经被选中
            cbSelected.isChecked = true
        }
        updateState(cbSelected)
        val ivCardContent = holder.getView<ImageView>(R.id.ivThumbnail)
        ImageLoader.loadImage(ivCardContent, item.filePath)
        holder.setText(R.id.tvTitle, item.name)
            .setText(R.id.tvFrom, item.dirName)
            .setText(R.id.tvSize,
                "${Utils.formatTime(item.duration)} ${Formatter.formatFileSize(holder.itemView.context, item.size)}")
        addChildClickViewIds(R.id.ivThumbnail)
        holder.itemView.setOnClickListener {
            cbSelected.setChecked(!cbSelected.isChecked)
            if (cbSelected.isChecked) {
                selectedItems[item.filePath] = item
            } else {
                selectedItems.remove(item.filePath)
            }
            updateState(cbSelected)
            onCheckChanged?.invoke(selectedItems.size)
        }
    }

    private fun updateState(imageView: CheckBox) {
        if (imageView.isChecked) {
            imageView.setButtonDrawable(R.drawable.ic_checkbox_checked)
        } else {
            imageView.setButtonDrawable(R.drawable.ic_compound_normal)
        }
    }

    fun selectAll() {
        data.forEach {
            selectedItems[it.filePath] = it
        }
        onCheckChanged?.invoke(selectedItems.size)
        notifyDataSetChanged()
    }

    fun selectNone() {
        selectedItems.clear()
        onCheckChanged?.invoke(selectedItems.size)
        notifyDataSetChanged()
    }

    fun getSelectedItems(): MutableList<VideoItem> {
        return selectedItems.values.toMutableList()
    }
}